package com.chefu.operator.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chefu.common.exception.pojo.LyException;
import com.chefu.common.pojo.PageResult;
import com.chefu.operator.mapper.ArticleCategoryMapper;
import com.chefu.operator.mapper.ArticleMapper;
import com.chefu.operator.pojo.ArticleCategory;
import com.chefu.operator.pojo.OperatorArticle;
import com.chefu.operator.vo.ArticleListVo;
import com.chefu.operator.vo.ArticleVo;
import com.chefu.operator.vo.ProductionVo;
import com.chefu.operator.vo.QueryArticlesRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArticleService {

    @Autowired(required = false)
    private ArticleMapper articleMapper;

    @Autowired(required = false)
    private ArticleCategoryMapper articleCategoryMapper;

    /**
     * 查询文章列表方法
     *
     * @param queryArticlesRequest
     * @return
     */
    public PageResult<ArticleListVo> queryArticlesByPage(QueryArticlesRequest queryArticlesRequest) {
        //1.构造查询对象
        OperatorArticle operatorArticle = new OperatorArticle();
        //2.封装查询条件
        BeanUtils.copyProperties(queryArticlesRequest, operatorArticle);
        Wrapper<OperatorArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.equals(operatorArticle);
        //3.查询数据库，返回符合条件的总记录数
        Integer total = articleMapper.selectCount(queryWrapper);
        //4.根据总记录数获得总页数
        Integer totalPage = null;
        Integer length = queryArticlesRequest.getRows();
        if (total / length == 0) {
            totalPage = total / queryArticlesRequest.getRows();
        } else {
            totalPage = (total / queryArticlesRequest.getRows()) + 1;
        }
        //5.进行分页查询
        Long start = (queryArticlesRequest.getPage() - 1) * queryArticlesRequest.getRows();//跳过的行数
        List<OperatorArticle> operatorArticleList = articleMapper.queryArticlesByPage(
                queryArticlesRequest.getTitle(),
                queryArticlesRequest.getCategory(),
                queryArticlesRequest.getReleaser(),
                queryArticlesRequest.getStatus(),
                queryArticlesRequest.getStartTime(),
                queryArticlesRequest.getEndTime(),
                start,
                length
        );

        //6.构造PageResult对象，判断operatorArticleList是否为空
        PageResult<ArticleListVo> pageResult = new PageResult<>();
        if (!operatorArticleList.isEmpty()) {
            //7.使用流式编程遍历operatorArticleList,将需要的数据封装到每一个ArticleListDTO，并返回List集合
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:MM:SS");//定义时间输出格式对象
            List<ArticleListVo> resultlist = operatorArticleList.stream().map(article -> {
                Long categoryId = article.getCategory();
                Long releaserId = article.getReleaser();
                ArticleListVo articleListVo = new ArticleListVo();
                //根据分类id查询类别名称，并封装到ArticleList对象中
                articleListVo.setCategory(articleCategoryMapper.selectById(categoryId).getCategoryName());
                //根据发布人id查询对应的名字并封装到ArticleList对象中（下面是伪代码）
                articleListVo.setReleaser("小明");
                //封装其余参数
                articleListVo.setId(article.getId());
                articleListVo.setTitle(article.getTitle());
                articleListVo.setCreatedTime(simpleDateFormat.format(article.getCreatedTime()));
//                articleListVo.setStatus(article.getStatus() == 1 ? "已发布" : "未发布");
                articleListVo.setStatus(article.getStatus());
                return articleListVo;
            }).collect(Collectors.toList());
            //8.封装参数
            pageResult.setItems(resultlist);
            pageResult.setTotal(total);
            pageResult.setTotalPage(totalPage);
        }
        return pageResult;
    }

    /**
     * 新增文章方法
     */
    public String addArticle(OperatorArticle operatorArticle) {
        //1.判断文章插入数据库
        Integer length = operatorArticle.getTitle().length();
        if (length<1||length>50) {
            //抛出异常，让前端捕获，弹窗提示用户
            throw new LyException(800,"文章标题必须是1到50个字符");
        }
        if (operatorArticle.getCategory() == null) {
            throw new LyException(801,"您必须为文章选择分类");
        }
        //2.插入数据库
        operatorArticle.setReleaser(5L);//通过本地线程获取userId,此处使用伪代码
        operatorArticle.setStatus(false);//默认状态为不发布
        articleMapper.insert(operatorArticle);
        return "新增文章成功";
    }

    /**
     *查看文章详情方法
     */
    public ArticleVo queryArticle(Long id) {
        //1.查询数据库
        OperatorArticle operatorArticle = articleMapper.selectById(id);
        //2.封装对象
        ArticleVo articleVo = new ArticleVo();
        if(operatorArticle!=null){
            articleVo.setId(operatorArticle.getId());
            articleVo.setTitle(operatorArticle.getTitle());
            //根据分类id查询分类
            ArticleCategory articleCategory = articleCategoryMapper.selectById(operatorArticle.getCategory());
            articleVo.setCategory(articleCategory.getCategoryName());
            articleVo.setArticlePicture(operatorArticle.getArticlePicture());
            //根据查询到的字符串使用“，”分割得到为id数组,查询配件表，下面伪代码
            ArrayList<ProductionVo> productionVos = new ArrayList<>();
            ProductionVo productionVo1 = new ProductionVo(1L, 100001, "博世火花塞", "XC1100001", "美孚金装1号", "1L", "机油", "美孚", 90L);
            ProductionVo productionVo2 = new ProductionVo(2L, 100001, "博世火花塞", "XC1100001", "美孚金装1号", "1L", "机油", "美孚", 90L);
            ProductionVo productionVo3 = new ProductionVo(3L, 100001, "博世火花塞", "XC1100001", "美孚金装1号", "1L", "机油", "美孚", 90L);
            ProductionVo productionVo4 = new ProductionVo(4L, 100001, "博世火花塞", "XC1100001", "美孚金装1号", "1L", "机油", "美孚", 90L);
            productionVos.add(productionVo1);
            productionVos.add(productionVo2);
            productionVos.add(productionVo3);
            productionVos.add(productionVo4);
            articleVo.setProduction(productionVos);
            articleVo.setArticleUrl(operatorArticle.getArticleUrl());
            articleVo.setArticleContent(operatorArticle.getArticleContent());
        }
        return articleVo;
    }

    /**
     *修改文章的方法
     */
    public String updateArticle(OperatorArticle operatorArticle) {
        //1.判断文章插入数据库
        Integer length = operatorArticle.getTitle().length();
        if (length<1||length>50) {
            //抛出异常，让前端捕获，弹窗提示用户
            throw new LyException(800,"文章标题必须是1到50个字符");
        }
        if (operatorArticle.getCategory() == null) {
            throw new LyException(801,"您必须为文章选择分类");
        }
        //2.更新数据库 发布人是否也需要修改，修改后的文章是否需要重新设置为未发布状态？
        articleMapper.updateById(operatorArticle);
        return "修改成功";
    }

    /**
     * 修改文章发布状态的方法
     */
    public void upadateStatus(Long id, Boolean saleable) {
        try {
            //1.创建OperatorArticle对象
            OperatorArticle operatorArticle = new OperatorArticle();
            operatorArticle.setStatus(saleable);
            operatorArticle.setId(id);
            //2.修改文章状态
            articleMapper.updateById(operatorArticle);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(803,"文章发布失败");
        }
    }

    /**
     * 查询文章分类列表的方法
     */
    public PageResult<ArticleCategory> queryCategoryByPage(Long page, Integer rows) {
        //1.封装分页查询
        IPage<ArticleCategory> ipage = new Page<>(page,rows) ;
        QueryWrapper<ArticleCategory> query=new QueryWrapper<>();
        //2.查询
        IPage<ArticleCategory> categoryIPage = articleCategoryMapper.selectPage(ipage, query);
        //3.封装分页数据
        PageResult<ArticleCategory> pageResult = new PageResult<>();
        pageResult.setTotalPage((int) categoryIPage.getPages());
        pageResult.setTotal((int) categoryIPage.getTotal());
        pageResult.setItems(categoryIPage.getRecords());
        return pageResult;
    }

    /**
     *新增文章分类
     */
    public String addArticleCategory(ArticleCategory articleCategory) {
        //1.判断分类名称长度
        int length = articleCategory.getCategoryName().length();
        if(length<1||length>10){
            throw new LyException(810,"文章分类名称必须为1到10个字符");
        }
        //2.插入数据库
        articleCategoryMapper.insert(articleCategory);
        return "新增文章成功";
    }

    /**
     * 修改文章分类
     */
    public String updateCategory(ArticleCategory articleCategory) {
        //1.判断分类名称长度
        int length = articleCategory.getCategoryName().length();
        if(length<1||length>10){
            throw new LyException(810,"文章分类名称必须为1到10个字符");
        }
        //2.插入数据库
        articleCategoryMapper.updateById(articleCategory);
        return "修改文章分类成功";
    }

    /**
     *删除文章分类
     */
    public String delCategory(Long id) {
        try {
            articleCategoryMapper.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(811,"删除文章分类出现异常");
        }
        return "删除成功";
    }
}
